package com.qf.dao;

import com.qf.pojo.Emp;
import com.qf.pojo.PageHelper;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 千锋健哥
 */
public class EmpDaoImpl implements EmpDao{

    //1. 创建全局的QueryRunner对象
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());


    @Override
    public List<Emp> findAll() {
        try {
            String sql = "select * from emp";
            List<Emp> list = queryRunner.query(sql, new BeanListHandler<Emp>(Emp.class));
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Emp findOne(Integer id) {
        try {
            String sql = "select * from emp where id=?";
            Emp emp = queryRunner.query(sql, new BeanHandler<Emp>(Emp.class), id);
            return emp;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void update(Emp emp) {
        try {
            String sql = "update emp set ";

            if (emp.getName() != null && !"".equals(emp.getName())) {
                sql = sql + "name='"+emp.getName() + "', ";
            }
            if (emp.getSalary() != null ) {
                sql = sql + "SALARY= "+emp.getSalary() + ", ";
            }
            if (emp.getAge() != null ) {
                sql = sql + "AGE = "+emp.getAge() ;
            }
            if (emp.getId() != null) {
                sql = sql + " WHERE id=" +emp.getId();
            }
            queryRunner.update(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Long selectCount() {
        try {
            String sql = "select count(*) from emp";
            Long count = queryRunner.query(sql, new ScalarHandler<Long>());
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Emp> selectPage(PageHelper pageHelper) {
        try {
            String sql = "select * from emp limit ?, ?";
            List<Emp> list = queryRunner.query(sql, new BeanListHandler<Emp>(Emp.class), pageHelper.getStartRows(),
                    pageHelper.getPageSize());
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}
